In this lesson, you learned about how a class is defined, and you covered the basic features of all C++ classes. You learned about these features of classes:
Project Listing 10. A simple class-based program.
1:// File name: PROJCT10.CPP
2:// An OOP program to list favorite radio stations
3://
4:#include <iostream.h>
5:#include <string.h>
6:
7://************************************************************
8:// String - a class to manage strings
9://
10:class String
11: {
12: public:
13: // Constructors
14: String(); // Default
15: String(const String& n); // Copy
16: String(const char * newString); // Normal
17: // Destructor
18: ~String();
19: // Access functions
20: const char * Get() const;
21: void Set(const char * newString);
22: int Length() const;
23: private:
24: // Data member
25: char * string;
26: };
27:
28:// Default constructor - ensure string is initialized
29:String::String()
30: {
31: string = 0;
32: }
33:
34:// Copy constructor - ensure string is duplicated
35:String::String(const String& n)
36: {
37: if (n.string)
38: {
39: string = new char[strlen(n.string) + 1];
40: strcpy(string,n.string);
41: }
42: else
43: string = 0;
44: }
45:
46:// Make a string from C string
47:String::String(const char * newString)
48: {
49: if (newString)
50: {
51: string = new char[strlen(newString) + 1];
52: strcpy(string,newString);
53: }
54: else
55: string = 0;
56: }
57:
58:// Destructor
59:String::~String()
60: {
61: delete [] string;
62: }
63:
64:// Provide access to stored string
65:const char * String::Get() const
66: {
67: return string;
68: }
69:// Replace contents with new string
70:void String::Set(const char * newString)
71: {
72: delete [] string;
73: if (newString)
74: {
75: string = new char[strlen(newString) + 1];
76: strcpy(string,newString);
77: }
78: else
79: string = 0;
80: }
81:// Get length of stored string
82:int String::Length() const
83: {
84: if (!string)
85: return 0;
86: return strlen(string);
87: }
88://************************************************************
89://
90://
91:class RadioStation
92: {
93: public:
94: RadioStation(const char * Name, const char * City,
95: float Frequency);
96: void Print() const;
97: private:
98: String name;
99: String city;
100: float frequency;
101: };
102:
103:RadioStation::RadioStation(const char * Name, const char * City,
104: float Frequency)
105: : name(Name),
106: city(City),
107: frequency(Frequency)
108: {
109: }
110:
111:void RadioStation::Print() const
112: {
113: int i;
114: cout << name.Get();
115: // Line up printout
116: for (i = name.Length(); i < 20; i++)
117: cout << ' ';
118: cout << city.Get();
119: for (i = city.Length(); i < 20; i++)
120: cout << ' ';
121: cout.precision(2); // NB cout is a class
122: // precision is a function
123: cout.setf(ios::showpoint);// as is setf
124: cout.setf(ios::fixed);
125: cout.width(6);
126: cout << frequency;
127: }
128://************************************************************
129:// Some global functions (they are still allowed in OOP!)
130://
131:int MoreInput();
132:RadioStation* NewRadioStation();
133:void PrintTitle();
134://************************************************************
135:// The main function
136://
137:void main()
138: {
139: RadioStation* stations[20]; // There are better ways to
140: // store lists, but this is
141: // good enough for this example
142: int count = 0;
143: while (MoreInput())
144: {
145: stations[count] = NewRadioStation();
146: if (!stations[count])
147: cout << "*** Error! Input rejected! ***" << endl;
148: else
149: count++;
150: }
151:
152: PrintTitle(); // Should this be global or part
153: // of RadioStation?
154:
155: for (int i = 0; i < count; i++)
156: {
157: stations[i]->Print(); // Call member function via pointer
158: cout << endl;
159: delete stations[i];
160: }
161: }
162:
163://************************************************************
164:// Globals
165://
166:int MoreInput()
167: {
168: char temp;
169: cout << endl << endl << "Do you want to add more stations? ";
170: cin >> temp;
171: cin.ignore();
172: if (temp == 'y' || temp == 'Y')
173: return 1;
174: else
175: return 0;
176: }
177:
178:RadioStation* NewRadioStation()
179: {
180: char tempName[81];
181: char tempCity[81];
182: float tempFrequency;
183: cout << endl << "Name: ";
184: cin.getline(tempName,81);
185: if (strlen(tempName) == 0)
186: return 0;
187: cout << "City: ";
188: cin.getline(tempCity,81);
189: if (strlen(tempCity) == 0)
190: return 0;
191: cout << "Frequency : ";
192: cin >> tempFrequency;
193: cin.ignore(80,'\n');
194: if (tempFrequency < 0)
195: return 0;
196: return new RadioStation(tempName,tempCity,tempFrequency);
197: }
198:
199:void PrintTitle()
200: {
201: cout << endl << "--------------------";
202: cout << "--------------------";
203: cout << "-----------" << endl;
204: cout << "Station ";
205: cout << "City ";
206: cout << "Frequency" << endl;
207: }
Output
Do you want to add more stations? y Name: Capital City: London Frequency : 95.8 Do you want to add more stations? y Name: Picadilly City: Manchester Frequency : 97.6 Do you want to add more stations? y Name: BRMB City: Birmingham Frequency : 98.8 Do you want to add more stations? y Name: *** Error! Input rejected! *** Do you want to add more stations? n --------------------------------------------------- Station City Frequency Capital London 95.80 Picadilly Manchester 97.60 BRMB Birmingham 98.80
Description
1: A comment to identify the program source file.
2: A comment to describe the program's purpose.
3: Empty comments enhance the appearance of the program.
4: Include the header for the cout functions.
5: Include the header required for strcpy and strlen().
6: Blank lines make the program more readable.
7: A bold comment separates each class.
8: A comment to describe the following class.
9: Empty comments enhance the appearance of the code.
10: Declare a class called String.
11: All class definitions start with an opening brace.
12: All members following this label will be public.
13: A comment to identify the following functions.
14: A default constructor is declared.
15: A copy constructor, which takes a reference to its own class.
16: A general constructor.
17: Comment to identify following functions.
18: The ~ in front of the class name and no return type identifies this function as a destructor.
19: Comment to identify following functions.
20: Get() is provided solely to access a private data member safely.
21: A function Set will be provided in this class, and a definition will follow.
22: An information function that provides the length of the string.
23: All members following this label will be public.
24: A comment to identify the following definition.
25: A pointer to a character string is defined as a class data member.
26: All class definitions end with a closing brace and a semicolon.
27: Blank lines help to make the program more readable.
28: A comment to identify the following function.
29: This line identifies that a member function of String is to be defined and that the function is the default constructor.
30: All functions start with an opening brace.
31: Ensure that the pointer is marked with zero for empty.
32: All functions end with a closing brace.
33: Blank lines make the code more readable.
34: A comment to describe the following code.
35: The definition of the class copy constructor starts.
36: All functions start with an opening brace.
37: If the passed string to be copied contains data, do the following:
38: Start a compound statement with an opening brace.
39: Create a new character array as long as the string to be copied plus an extra character for the terminator.
40: Copy the actual string into the new class storage.
41: End a compound statement with a closing brace.
42: If the string pointer does not point to data, do the following.
43: Set the new string pointer to zero so that C++ can later identifiy that no memory is allocated to this pointer.
44: Function definitions always end with a closing brace.
45: Blank lines make the program more readable.
46: A comment to describe the following function.
47: Define the class constructor that accepts a const char* parameter.
48: All functions start with an opening brace.
49: If a non-zero string is passed, do the following:
50: Compound statements start with an opening brace.
51: Create a new character storage that is long enough to contain the string passed in.
52: Copy the string.
53: Compound statements end with a closing brace.
54: If the string pointer does not point to data, do the following.
55: Set the new string pointer to zero so that C++ can later identifiy that no memory is allocated to this pointer.
56: All functions end with a closing brace.
57: Blank lines help to make the program more readable.
58: A comment to describe the following function.
59: A function with the same name as the class name and a ~ in front declares a destructor.
60: Function definitions always start with an opening brace.
61: An array is deleted with the array deletion operator.
62: C++ functions are typically very short, as this closing brace shows.
63: Blank lines make the program more readable.
64: Comments explain the actions of the code
65: Define a function that retrieves a pointer to a string that cannot be used to update.
66: All function definitions start with an opening brace.
67: Returning a non-const value causes the return value to be automatically cast into const by the compiler.
68: All functions end with a closing brace.
69: Use comments to explain the workings of the code.
70: Define a function with no return value, which accepts a literal (or variable) string.
71: All functions start with an opening brace.
72: Remove the existing contents of the string pointer. delete does not operate on a zero pointer.
73: If the parameter passes an actual string, do the following:
74: Compound statements start with an opening bracket.
75: Create a dynamic allocation as long as the passed string plus the terminator.
76: Copy the parameter into the allocated storage.
77: Compound statements are ended with a closing brace.
78: If no string was passed, a zero pointer is received. Perform the following step.
79: Set the pointer to zero.
80: All functions end with a closing brace.
81: Comment to explain the workings of the program.
82: Declare a function that returns an int and takes no parameters.
83: All functions start with an opening brace.
84: If no string is stored by the class, do the following:
85: Return a zero length, avoiding checking a missing string.
86: Return the length found by a library function.
87: All functions end with a closing brace.
88: A comment helps delimit sections of code.
89: Empty comments can enhance the appearance of the program.
90: Empty comments can enhance the appearance of the program.
91: Declare a class called RadioStation.
92: All class definitions start with an opening brace.
93: All functions following this label will be public.
94: Declare a constructor for the class.
95: Long declarations are best split over a number of lines.
96: Declare a public member function.
97: All members following this label will be private.
98: Declare a member that is a class of your own making.
99: Declare a String data member.
100: Declare a data member of type float.
101: All class definitions end with a closing brace and a semicolon.
102: Blank lines enhance the appearance of the program.
103: Define the radioStation constructor.
104: Long parameter lists are best split over a number of lines.
105: Members are very efficiently initialized using class constructors in an initialization list.
106: Initialize the city String with the String constructor.
107: Standard classes also have constructors that can be directly called.
108: All function definitions must start with an opening brace even though they might do nothing.
109: All function definitions must end with a closing brace even if they do nothing.
110: Blank lines make the program more readable.
111: Define a function that has been declared part of the RadioStation class.
112: All functions start with an opening brace.
113: Declare a variable i for later use.
114: Output a character string obtained from the string name.
115: Comments explain the workings of the program.
116: Do the following statement for the number of characters in the string up to 19.
117: Output a space to line up the list for names of different lengths.
118: Print the city name retrieved from the string member.
119: Do the following statement for the number of characters in the string up to 19.
120: Output a space to line up the list for city names of different lengths.
121: Use built-in class member function of cout to set the number of decimal places printed.
122: Comments explain the working of the program.
123: Ensure that the decimal place is always shown.
124: Stop numbers from being displayed in floating-point format.
125: Limit the number of characters for displaying the number to six.
126: Output the number according to the previous formatting.
127: All functions end with a closing brace.
128: Bold comments help divide the sections of the program.
129: Attempts at witty comments become irritating over time.
130: Blank comments enhance the appearance of your code.
131: Prototype a global function.
132: Prototype a global function.
133: Breaking up large functions into several routines makes the program easier to follow.
134: Bold comments help divide the sections of the program.
135: A comment can title the following code.
136: Blank comments enhance the appearance of your code.
137: Define the main() function where the program starts executing.
138: A function definition always starts with an opening brace.
139: A declaration of an array of 20 RadioStation pointers.
140: A comment to explain the way the program has been coded.
141: A comment to explain the way the program has been coded.
142: A counter to record the number of stations entered.
143: while the user requests further input.
144: Multiple statements repeated by a while loop need to be enclosed in a compound statement.
145: Allocate a new radio station using a function defined later.
146: If the program was not able to allocate a new radio station. . .
147: Report the error to the user.
148: If the program was able to allocate the new radio station. . .
149: Increment the count of successfully added radio stations.
150: This closing brace marks the end of a while loop.
151: Blank lines help to make the program more readable.
152: Call a global routine to output the title of the report.
153: Use comments to note places where the code might be improved in the future.
154: Blank lines help to make the program more readable.
155: For each radio station stored, do the following:
156: Loops requiring multiple statements need compound statements.
157: Call the member function of RadioStation using the pointer access operator.
158: Output a newline sequence.
159: Delete the allocated memory when it is no longer required.
160: The closing brace marks the end of the for loop.
161: Closing braces also mark the end of function definitions.
162: Blank lines make programs more readable.
163: Bold comments separate sections of the program.
164: A comment is used to title the following code.
165: Blank comments can enhance the appearance of your program.
166: Define a global function that returns true (nonzero) or false(zero).
167: Function definitions always start with an opening brace.
168: A variable to test the user input.
169: Prompt the user for an answer with a question.
170: Get the first character of input.
171: Ignore all input after the first character.
172: If the answer is lower- or uppercase Y. . .
173: Return true
174: Otherwise. . .
175: Return false.
176: All function definitions end with a closing brace.
177: Blank lines help to make your programs more readable.
178: Declare a function that returns a pointer to a RadioStation.
179: All function declarations start with an opening brace.
180: Declare a temporary character string big enough for any response.
181: Declare a temporary character string big enough for any response.
182: Declare a temporary variable for the frequency of the station.
183: Prompt the user to enter the name of the station.
184: Get the name of the station.
185: If name is zero length. . .
186: Reject the input.
187: Prompt for city name.
188: Get the city name entered by the user.
189: If name is zero length. . .
190: Reject the input.
191: Prompt the user to enter the frequency.
192: Get the frequency from the user.
193: Ignore any extra characters entered after the user enters the frequency.
194: If frequency is nonsense. . .
195: Reject the input.
196: If the input is acceptable, return a new RadioStation object via a temporary hidden pointer.
197: All functions end with a closing brace.
198: Blank lines make the program more readable.
199: Define the PrintTitle() global function.
200: All function definitions start with an opening brace.
201: Output a newline sequence and text.
202: Output text.
203: Output text and a newline.
204: Output text.
205: Output text.
206: Output text and a newline.
207: All functions end with a closing brace.
14: A constructor can always be identified because it has no return type and has the same name as the class.
16: A constructor that takes a single parameter can also be used as a type converter.
31: A pointer with valid storage can never be zero.
49: When accepting pointers, it is a good idea to check that a value has been passed.
72: delete does not operate on a zero pointer.
79: delete does not reset the pointer to zero.
113: It is a tradition from FORTRAN and BASIC that integer counters are named i.
132: Of course, global functions can still see and use class object definitions.
143: This should test for the array bound. How would you code that?
165: Many libraries of code and new ANSI draft of C++ declare a type BOOL or bool with values of TRUE and FALSE or true and false.
184: Using getline() allows the name to contain blanks.
196: If the function can't allocate memory, zero will be returned.